package com.m3839.sdk.common.widget.richtext;

import android.text.Spanned;
import android.util.Log;

import org.xml.sax.XMLReader;

import java.lang.reflect.Field;

/**
 * html标签解析工具
 *
 * @author 徐智伟
 * @create 2020-03-27
 */
public final class HtmlTagHelper {
  public static final String TAG = "HtmlTagHelper";


  public static <T> T getLast(Spanned text, Class<T> kind) {

    T[] objs = text.getSpans(0, text.length(), kind);
    if (objs.length == 0) {
      return null;
    } else {
      return objs[objs.length - 1];
    }
  }


  /**
   * 获取标签的属性值
   * @param xmlReader
   * @param attrName
   * @return
   */
  public static String getAttribute(XMLReader xmlReader, String attrName) {
    return getAttribute(xmlReader, attrName, null);
  }

  public static String getAttribute(XMLReader xmlReader, String attrName, String defaultAttr) {
    try {
      final Field elementField = xmlReader.getClass().getDeclaredField("theNewElement");
      elementField.setAccessible(true);
      final Object element = elementField.get(xmlReader);
      final Field attsField = element.getClass().getDeclaredField("theAtts");
      attsField.setAccessible(true);
      final Object atts = attsField.get(element);
      final Field dataField = atts.getClass().getDeclaredField("data");
      dataField.setAccessible(true);
      final String[] data = (String[]) dataField.get(atts);
      final Field lengthField = atts.getClass().getDeclaredField("length");
      lengthField.setAccessible(true);
      final int len = (Integer) lengthField.get(atts);
      for(int i = 0; i < len; i++) {
        if(attrName.equals(data[i * 5 + 1])) {
          return data[i * 5 + 4];
        }
      }
    } catch(Exception e) {
      Log.e(TAG, "handleTag: ", e);
    }
    return defaultAttr;

  }
}
